<script setup lang="ts">
import { ref, onMounted, onUnmounted } from 'vue'
import ChatRoom from '../components/ChatRoom.vue'
import { aiApi, generateChatId } from '../services/api'

// 生成聊天ID
const chatId = ref(generateChatId())
const chatRoomRef = ref<InstanceType<typeof ChatRoom> | null>(null)
let eventSource: EventSource | null = null

// 发送消息并处理SSE响应
const handleSendMessage = (message: string) => {
  // 关闭之前的连接
  if (eventSource) {
    eventSource.close()
  }
  
  // 创建新的SSE连接
  eventSource = aiApi.chatWithSSE(message, chatId.value)
  
  let accumulatedResponse = '' // 累积响应
  let responseStarted = false
  
  // 监听SSE事件
  eventSource.onmessage = (event) => {
    if (event.data && chatRoomRef.value) {
      // 累积响应内容
      accumulatedResponse += event.data
      
      // 如果是第一次收到响应，创建新的AI回复气泡
      if (!responseStarted) {
        chatRoomRef.value.addAIMessage(accumulatedResponse)
        responseStarted = true
      } else {
        // 否则更新最后一条AI消息
        chatRoomRef.value.updateExistingAIMessage(accumulatedResponse)
      }
    }
  }
  
  // 处理错误
  eventSource.onerror = (error) => {
    console.error('SSE错误:', error)
    if (eventSource) {
      eventSource.close()
    }
  }
}

// 组件销毁时关闭SSE连接
onUnmounted(() => {
  if (eventSource) {
    eventSource.close()
  }
})
</script>

<template>
  <ChatRoom 
    ref="chatRoomRef"
    :chatId="chatId" 
    title="AI少儿编程助手"
    :isSmartAgent="false"
    @send-message="handleSendMessage" 
  />
</template>

<style scoped>
.kids-coding-view {
  height: 100%;
  padding: 20px;
  max-width: 1000px;
  margin: 0 auto;
}

@media (max-width: 768px) {
  .kids-coding-view {
    padding: 10px;
  }
}
</style> 